package icu.xblogs.report.controller;

import com.auth0.jwt.JWT;
import icu.xblogs.report.domain.Employee;
import icu.xblogs.report.service.AttendanceRecordService;
import icu.xblogs.report.service.EmployeeService;
import icu.xblogs.report.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author Frank KONG
 * @version 1.0
 * @date 2020/11/18 15:01
 *
 * 嵌入式平台与服务器通信
 */
@Controller
public class EmbeddedController {

    AttendanceRecordService attendanceRecordService;

    EmployeeService employeeService;

    @Autowired
    @Qualifier("attendanceRecordService")
    public void setAttendanceRecordService(AttendanceRecordService attendanceRecordService) {
        this.attendanceRecordService = attendanceRecordService;
    }

    @Autowired
    @Qualifier("employeeService")
    public void setEmployeeService(EmployeeService employeeService) {
        this.employeeService = employeeService;
    }

    @RequestMapping("/report")
    @ResponseBody
    public String report(int id, @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")  Date date, String token){
        System.out.println(date);
        Employee employee = employeeService.getById(id);
        if(employee == null) return "101"; //查无此人
        if(JwtUtil.getJWT(String.valueOf(id)).equals(token)){
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat accurateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String day = dateFormat.format(date);
            String accurateTime = accurateTimeFormat.format(date);
            if(attendanceRecordService.countByDate(id, day) > 0){
                return "102";//今日已打卡
            }else{
                attendanceRecordService.insertOneRecord(id, accurateTime, day);
                return "100:" + employee.getName();//打卡成功
            }
        }
        return "400";//其它错误
    }

}
